#include <iostream>
#include <queue>
#include <vector>
using namespace std;
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        if (!root)return 0;
        queue<pair<TreeNode*, unsigned long long>> q;
        q.push({ root,0 });
        int maxlen = 0;
        while (!q.empty()) {
            int levelsize = q.size();
            unsigned long long left = q.front().second;
            unsigned long long right = left;
            for (int i = 0; i < levelsize; i++) {
                TreeNode* node = q.front().first;
                auto idx = q.front().second;
                q.pop();
                right = idx;
                unsigned long long normalizeidx = idx - left;
                if (node->left) {
                    q.push({ node->left, normalizeidx * 2 });
                }
                if (node->right) {
                    q.push({ node->right, normalizeidx * 2 + 1 });
                }
            }
            int width = right - left + 1;
            maxlen = max(maxlen,width);
        }
        return maxlen;
    }
};